package com.sj.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021/5/11
 * Time: 下午 17:59
 * Description: Jwt工具类
 */
@Data
@Component
@ConfigurationProperties(prefix = "sjblog.jwt")
public class JwtUtils {
    // 秘钥
    private String secret;
    // 过期时间
    private Long expire;
    // 头名字
    private String header;

    /**
     * 生成token
     *
     * @param sub 接收用户
     * @return token值
     */
    public String generateToken(String sub) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(sub)
                .setIssuedAt(new Date())
                .setExpiration(new Date(new Date().getTime() + expire * 1000))
                .signWith(SignatureAlgorithm.HS256, secret).compact();
    }

    /**
     * 解析token
     *
     * @param token 需要解析的token字符串
     * @return
     */
    public Claims resolverToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断token是否失效
     *
     * @param claims
     * @return
     */
    public boolean tokenIsExpired(Claims claims) {
        // 失效时间是否在当前时间之前
        return claims.getExpiration().before(new Date());
    }


}